package DatabaseAccess;

import java.sql.*;

public class SQLHelper {
    
    private static Connection myConn = MyConnection.getInstance().getConnection();
    private static CallableStatement objCall;
    private static ResultSet objResult;
    private static String stringSQL;

    public static ResultSet executeQuery(String procName, Object parameters) {
        createStringSQL(procName, parameters);
        createParameter(parameters);
        try {
            objResult = objCall.executeQuery();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return objResult;
    }

    public static CallableStatement execute(String procName, Object parameters) {
        createStringSQL(procName, parameters);
        createParameter(parameters);
        try {
            objCall.execute();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return objCall;
    }

    public static int executeUpdate(String procName, Object parameters) {
        createStringSQL(procName, parameters);
        createParameter(parameters);
        try {
            return objCall.executeUpdate();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return 0;
    }

    private static void createStringSQL(String procName, Object parameters) {
        stringSQL = "{ call " + procName;
        if (parameters != null) {
            stringSQL += "(";
            for (int i = 0; i < ((String[]) parameters).length; i++) {
                stringSQL += "?,";
            }
            stringSQL = stringSQL.substring(0, stringSQL.length() - 1) + ")";
        }
        stringSQL += " }";
    }

    private static void createParameter(Object parameters) {
        try {
            objCall = myConn.prepareCall(stringSQL);
            if (parameters != null) {
                for (int i = 0; i < ((String[]) parameters).length; i++) {
                    if (((String[]) parameters)[i] != null) {
                        objCall.setString((i + 1), ((String[]) parameters)[i]);
                    } else {
                        objCall.registerOutParameter((i + 1), Types.SMALLINT);
                    }
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}
